<template>
  <section class="wrap">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input disabled v-model="ruleForm.orderNo" />
      </el-form-item>
      <el-form-item label="游戏类型" prop="gameType">
        <el-select style="width: 100%;" v-model="ruleForm.gameType" placeholder="请选择游戏类别" disabled>
          <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="游戏" prop="gameId">
        <el-select disabled style="width: 100%;" v-model="ruleForm.gameId" placeholder="请选择游戏" @change="changeGame">
          <el-option v-for="item in filterGameList(ruleForm.gameType)" :key="'game' + item.id" :label="item.gameName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="游戏账号" prop="gameAccount">
        <el-input disabled v-model="ruleForm.gameAccount" />
      </el-form-item>
      <el-form-item label="游戏Id" prop="laobanyouxiid">
        <el-input disabled v-model="ruleForm.laobanyouxiid" />
      </el-form-item>
      <el-form-item label="订单金额" prop="price">
        <el-input v-model="ruleForm.price" type="number" disabled />
      </el-form-item>
      <el-form-item label="打手佣金" prop="dashouyongjin">
        <el-input v-model="ruleForm.dashouyongjin" type="number" disabled />
      </el-form-item>
      <el-form-item label="单排/双排" prop="playerNum">
        <el-select style="width: 100%;" v-model="ruleForm.playerNum" placeholder="请选择单排/双排" disabled>
          <el-option v-for="item in paiwei" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="语音频道" prop="channel">
        <el-select style="width: 100%;" v-model="ruleForm.channel" placeholder="请选择语音频道" disabled>
          <el-option v-for="item in channelOption" :key="item.label" :label="item.label" :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="payment">
        <el-select style="width: 100%;" v-model="ruleForm.payment" placeholder="请选择语音频道" disabled>
          <el-option v-for="item in zhifufangshi" :key="item.label" :label="item.label" :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="指定打手" prop="playerId">
        <el-select style="width: 100%;" :disabled="ruleForm.orderStatus !== 1" multiple
          :multiple-limit="ruleForm.playerNum || 1" v-model="zhidingdashou" placeholder="请指定打手">
          <el-option v-for="item in getUser(2)" :key="'user' + item.id" :label="item.nickName" :value="item.id + ''">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发单人" prop="playerId">
        <el-select style="width: 100%;" v-model="ruleForm.userId" placeholder="请选择发单人" disabled>
          <el-option v-for="item in getUser(null)" :key="'user' + item.id" :label="item.nickName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单备注" prop="createRemark">
        <el-input v-model="ruleForm.createRemark" :disabled="ruleForm.orderStatus !== 1" />
      </el-form-item>
      <el-form-item label="打手上传图片" v-if="ruleForm.playerImg && ruleForm.orderStatus === 3">
        <template>
          <img style="width: 300px;" :src="ruleForm.playerImg" alt="" srcset="">
        </template>
      </el-form-item>
      <el-form-item label="打手备注" v-if="ruleForm.playerRemark && ruleForm.orderStatus === 3">
        <template>
          <el-input v-model="ruleForm.playerRemark" :disabled="ruleForm.orderStatus !== 1" />
        </template>
      </el-form-item>
      <el-form-item>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        <el-button type="primary" :loading="submitting" v-if="ruleForm.orderStatus === 1"
          @click="submitForm('ruleForm')">立即更新</el-button>
        <el-button type="primary" :loading="submitting" v-if="ruleForm.orderStatus === 3"
          @click="wancheng">完成订单</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
import { hostURL } from '@/plugins/utils/config'
import userApi from '@/plugins/api/user'
import dealApi from '@/plugins/api/deal'
import orderApi from '@/plugins/api/order' // 添加缺失的导入
import gameApi from '@/plugins/api/game'
import { orderCaozuo } from '@/plugins/utils/caozuojilu'
export default {
  name: 'UserCreate',
  data() {
    return {
      token: '',
      zhidingdashou: [],
      userList: [],
      listLoading: false, // 添加缺失的变量
      submitting: false, // 提交状态
      uploadUrl: hostURL + '/upload/images',
      option: [
        {
          label: '端游',
          value: 1
        },
        {
          label: '手游',
          value: 2
        },
      ],
      paiwei: [
        {
          label: '单排',
          value: 1
        },
        {
          label: '双排',
          value: 2
        },
      ],
      channelOption: [
        {
          label: 'kook'
        },
        {
          label: 'yy'
        },
        {
          label: '游戏麦'
        },
      ],
      zhifufangshi: [
        {
          label: '闲鱼下单'
        },
        {
          label: '闲鱼转账'
        },
        {
          label: '支付宝转账'
        },
        {
          label: '微信转账'
        },
      ],
      gameOptions: [],
      allUser: [],
      ruleForm: {
        gameType: null,       // 游戏类型（选择值）
        gameId: null,         // 游戏ID（选择值）
        gameAccount: '',      // 游戏账号（输入值）
        laobanyouxiid: '',    // 游戏Id（输入值）
        price: '',             // 订单金额（数字，禁用）
        dashouyongjin: '',     // 打手佣金（数字，禁用）
        playerNum: null,      // 单排/双排（选择值）
        channel: '',        // 语音频道（选择值）
        payment: '',        // 支付方式（选择值）
        playerId: '',
        userId: null,    // 发单人ID（选择值）
        createRemark: ''      // 订单备注（输入值）
      },
      currentGame: {},
      rules: {
        gameType: [
          { required: true, message: '请选择游戏平台', trigger: 'change' }
        ],
        gameId: [
          { required: true, message: '请选择游戏', trigger: 'change' }
        ],
        gameAccount: [
          { required: true, message: '请输入游戏账号', trigger: 'blur' },
        ],
        laobanyouxiid: [
          { required: true, message: '请输入老板游戏ID', trigger: 'blur' },
        ],
        playerNum: [
          { required: true, message: '请选择排位模式', trigger: 'change' }
        ],
        channel: [
          { required: true, message: '请选择语音频道', trigger: 'change' }
        ],
        payment: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        userId: [
          { required: true, message: '请选择发单人', trigger: 'change' }
        ],
      }
    }
  },
  mounted() {
    this.getGameList()
    this.getAllUser()
    this.getOrder()
  },
  methods: {

    async wancheng() {
      const that = this
      const arr = that.ruleForm.playerId.split(',')
      const game = that.gameOptions.find(item => item.id === that.ruleForm.gameId)

      let player1 = that.allUser.find(item => item.id === Number(arr[0]))
      let player2 = arr.length > 1 ? that.allUser.find(item => item.id === Number(arr[0])) : null
      that.payToPlayer(player1, game.days, that.ruleForm.playerNum, that.ruleForm.dashouyongjin)
      if (player2 !== null) {
        that.payToPlayer(player2, game.days, that.ruleForm.playerNum, that.ruleForm.dashouyongjin)
      }
      if (that.ruleForm.userId) {
        let fadanren = that.allUser.find(item => item.id === Number(that.ruleForm.userId))
        that.deal(fadanren, Number(that.ruleForm.price) - Number(that.ruleForm.dashouyongjin))
      }

      that.ruleForm.orderStatus = 4
      const res = await orderApi.modify(that.ruleForm)
      if (res.code === 200) {
        await orderCaozuo.update(that.ruleForm)
        that.$message.success('订单更新成功')
      } else {
        that.$message.success('订单更新失败')
      }
    },

    async payToPlayer(player, days, playerNum, dashouyongjin) {
      const that = this
      let price = Number(dashouyongjin) / Number(playerNum)
      if (player.parent) {
        const yaoqingren = this.allUser.find(item => item.id === player.parent)
        if (days) {
          yaoqingren.dongjie = Number(price) * 0.01
          player.dongjie = Number(price) * 0.99
        } else {
          yaoqingren.weijiesuan = Number(price) * 0.01
          player.weijiesuan = Number(price) * 0.99
        }
        that.deal(yaoqingren, Number(price) * 0.01)
        that.deal(yaoqingren, Number(price) * 0.01)
      } else {
        if (days) {
          player.dongjie = price
        } else {
          player.weijiesuan = price
        }
        that.deal(player, price)
      }
    },

    async deal(user, price, days) {
      const dealobj = {
        userId: user.id,
        value: price,
        createTime: new Date().getTime(),
        type: 2
      }
      const res = await dealApi.modify(dealobj)
      if (res.code === 200) {
        await userApi.update(user)
      }
    },

    getOrder() {
      this.ruleForm = JSON.parse(localStorage.getItem('order'))
      this.zhidingdashou = this.ruleForm.playerId ? this.ruleForm.playerId.split(',') : []
    },

    // 上传图片成功回调
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.ruleForm.avr = res.data.img_url // 修正字段名
        this.$message.success('上传成功!')
      } else {
        this.$message.error(res.message || '上传失败')
      }
    },

    filterGameList(type) {
      return this.gameOptions.filter(item => item.type === type)
    },

    changeGame() {
      this.currentGame = this.gameOptions.find(item => item.id === this.ruleForm.gameId)
      this.ruleForm.price = Number(this.currentGame.price).toFixed(2)
      this.ruleForm.dashouyongjin = (Number(this.currentGame.price) * 0.9).toFixed(2)
    },

    getUser(role) {
      if (!role) {
        return this.allUser.filter(item => item.role === 1 || item.role === 3)
      }
      return this.allUser.filter(item => item.role === role)
    },

    async getGameList() {
      const res = await gameApi.list()
      console.log('res -> ', res);
      if (res.code === 200) {
        this.gameOptions = res.data
      } else {
        this.$message.error('获取游戏列表出错')
      }
    },

    async getAllUser() {
      const res = await userApi.all()
      console.log('getAllUser -> ', res);
      if (res.code === 200) {
        this.allUser = res.data
      } else {
        this.$message.error('获取用户列表出错')
      }
    },


    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.create()
        } else {
          this.$message.warning('请填写完整表单信息')
          return false
        }
      })
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    // 更新订单
    async create() {
      if (this.zhidingdashou.length) {
        this.ruleForm.playerId = this.zhidingdashou.join(',')
      }
      if (this.zhidingdashou.length == this.ruleForm.playerNum && this.ruleForm.orderStatus === 1) {
        this.ruleForm.orderStatus = 2
      }
      console.log(this.ruleForm);
      this.submitting = true
      try {
        const res = await orderApi.modify(this.ruleForm)
        if (res.code === 200) {
          await orderCaozuo.update(this.ruleForm)
          await this.$confirm('更新成功，是否退出更新订单页面', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'success'
          })

          this.$router.push('/order/index')
        } else {
          this.$message.error(res.message || '更新失败')
        }
      } catch (err) {
        console.error('更新订单失败:', err)
        this.$message.error(err.message || '更新订单失败')
      } finally {
        this.submitting = false
      }



    }
  }
}
</script>

<style scoped lang="scss">
.wrap {
  box-sizing: border-box;
  margin: 24px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>